<?php
class BookingsController extends AppController
{
    var $uses = array('Booking', 'Customer', 'Location', 'Hotel', 'BookingStatus', 'PaymentType', 'BookingDetail');
    var $components = array('Email');

    var $paginate = array(
        'limit' => 20,
        'order' => array(
            'Booking.created' => 'desc'
        )
    );

    function  beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('eticket');
        $hide = '';
        if ($this->Session->read('Auth.User.role') != 'admin')
        {
            $hide = ' hide';
        }
        $this->set('hide', $hide);
    }
    
    function index()
    {
        if (isset($this->params['named']['month']))
        {
            $this->data['Booking']['month'] = $this->params['named']['month'];
        }
        if (isset($this->params['named']['year']))
        {
            $this->data['Booking']['year'] = $this->params['named']['year'];
        }
        if (isset($this->params['named']['query']))
        {
            $query = $this->params['named']['query'];
            //$query = htmlspecialchars_decode($query);
            $this->set('query', $query);

            $conditions = array();
            //$conditions['Customer.information LIKE'] = '%' . mysql_real_escape_string(trim($query)) . '%';
            $query_string = explode(',', $query);
            $count = 1;
            foreach ($query_string as $search_string)
            {
                $conditions[] = array('CONCAT(Customer.last_name, " ", Customer.first_name, " ", Booking.alo_booking_code, " ", Booking.hotel_booking_code) LIKE' => "%" . mysql_real_escape_string(trim($search_string)) . "%");
                $count++;
            }

            if ($this->data['Booking']['month'] != 'all' && is_numeric($this->data['Booking']['month']))
            {
                $conditions[] =  array('Booking.month' => $this->data['Booking']['month']);
            }

            if ($this->data['Booking']['year'] != 'all' && is_numeric($this->data['Booking']['year']))
            {
                $conditions[] =  array('Booking.year' => $this->data['Booking']['year']);
            }

            $this->paginate = array(
                'limit' => 20,
                'order' => array(
                    'Booking.created' => 'desc'
                ),
                'conditions' => $conditions,
                //'conditions' => $conditions
            );
        }

        $date_conditions = array();
        if ($this->data['Booking']['month'] != 'all' && is_numeric($this->data['Booking']['month']))
        {
            $date_conditions[] =  array('Booking.month' => $this->data['Booking']['month']);
        }

        if ($this->data['Booking']['year'] != 'all' && is_numeric($this->data['Booking']['year']))
        {
            $date_conditions[] =  array('Booking.year' => $this->data['Booking']['year']);
        }

        $all_bookings = $this->Booking->find('all', array('conditions' => $date_conditions));
        $this->set('all_bookings', $all_bookings);

        $total_profit = 0.0;
        foreach ($all_bookings as $booking)
        {
            $total_price = 0.0;
            $total_original_price = 0.0;
            foreach ($booking['BookingDetail'] as $booking_detail)
            {
                if ($booking['Booking']['currency'] == 'USD')
                {
                    $total_price += (float)$booking_detail['price'] * $booking['Booking']['alo_exchange_rate'];
                    $total_original_price += (float)$booking_detail['original_price'] * $booking['Booking']['hotel_exchange_rate'];
                }
                else
                {
                    $total_price += (float)$booking_detail['price'];
                    $total_original_price += (float)$booking_detail['original_price'];
                }
            }
            $profit = $total_price - $total_original_price;
            $this->Booking->id = $booking['Booking']['id'];
            $this->Booking->save(array('total_price' => $total_price, 'total_original_price' => $total_original_price, 'profit' => $profit));
            $this->Booking->id = null;
            $total_profit += $profit;
        }
        $this->set('total_profit', $total_profit);

        $month['all'] = 'Tất cả';
        for ($i = 1; $i <= 12; $i++)
        {
            $month[$i] = 'Tháng ' . $i;
        }
        $this->set('month', $month);

        $year['all'] = 'Tất cả';
        for ($i = 2008; $i <= 2018; $i++)
        {
            $year[$i] = 'Năm ' . $i;
        }
        $this->set('year', $year);

        $this->paginate = array(
            'limit' => 20,
            'order' => array(
                'Booking.created' => 'desc'
            ),
            'conditions' => $conditions,
            //'conditions' => $conditions
        );

        $bookings = $this->paginate('Booking');
        $this->set('bookings', $bookings);

    }

    function add()
    {
        $today = date('d/m/y', time());
        $this->set('today', $today);

        if (empty($this->data['Booking']['date']))
        {
            $this->data['Booking']['date'] = $today;
        }

        $customer_code = $this->AloCode->generateCustomerCode();
        $this->set('customer_code', $customer_code);

        $alo_booking_code = $this->AloCode->generateBookingCode();
        $this->set('alo_booking_code', $alo_booking_code);

        $action = !empty($this->data['Action']['do']) ? $this->data['Action']['do'] : '';

        $customers = $this->Customer->find('all');
        $this->set('customers', $customers);

        $selected_customer = null;

        if ($action == 'add_customer')
        {
            $this->layout = 'ajax';
            if ($this->Customer->save($this->data))
            {
                //$this->flash('Tạo khách hàng thành công!', '');
                $this->set('success_msg', 'Tạo khách hàng thành công!');
                $customer['Customer'] = $this->data['Customer'];
                $customer['Customer']['id'] = $this->Customer->id;
                $this->data['Customer'] = null;
                $this->set('selected_customer', $customer);
                $selected_customer = $customer;
            }
            else
            {
                if (!empty($this->params['named']['query']))
                {
                    $query = $this->params['named']['query'];
                    //$query = htmlspecialchars_decode($query);
                    $this->set('query', $query);

                    $conditions = array();
                    //$conditions['Customer.information LIKE'] = '%' . mysql_real_escape_string(trim($query)) . '%';
                    $query_string = explode(',', $query);
                    $count = 1;
                    foreach ($query_string as $search_string)
                    {
                        $conditions[] = array('Customer.information LIKE' => "%" . mysql_real_escape_string(trim($search_string)) . "%");
                        $count++;
                    }

                    $customer = $this->Customer->find('first', array('conditions' => array('OR' => $conditions)));
                    $selected_customer = $customer;
                    $this->set('selected_customer', $customer);
                }
            }
            $this->render('select_customer');
        }

        else if ($action == 'update_booking_info_left')
        {
            $this->layout = 'ajax';

            $location_id = 'all';
            
            if (!empty($this->params['named']['location_id']))
            {
                $location_id = $this->params['named']['location_id'];
                $this->data['Booking']['location_id'] = $location_id;
            }

            $hotel_conditions = array();
            if ($location_id != 'all' && is_numeric($location_id))
            {
                $hotel_conditions = array('Hotel.location_id' => $location_id);
            }

            $locations['all'] = 'Chọn địa điểm';
            $locations += $this->Location->find('list');
            $this->set('locations', $locations);

            $hotels['all'] = 'Chọn khách sạn';
            $hotels += $this->Hotel->find('list', array('conditions' => $hotel_conditions));
            $this->set('hotels', $hotels);
            
            $this->render('booking_info_left');
        }

        else if ($action == 'find_customer')
        {
            $this->layout = 'ajax';
            if (!empty($this->params['named']['query']))
            {
                $query = $this->params['named']['query'];
                //$query = htmlspecialchars_decode($query);
                $this->set('query', $query);

                $conditions = array();
                //$conditions['Customer.information LIKE'] = '%' . mysql_real_escape_string(trim($query)) . '%';
                $query_string = explode(',', $query);
                $count = 1;
                foreach ($query_string as $search_string)
                {
                    $conditions[] = array('Customer.information LIKE' => "%" . mysql_real_escape_string(trim($search_string)) . "%");
                    $count++;
                }

                $customer = $this->Customer->find('first', array('conditions' => array('OR' => $conditions)));
                $selected_customer = $customer;
                $this->set('selected_customer', $customer);
            }
            $this->render('select_customer');
        }

        else if ($action == 'add_booking')
        {
            if (!empty($this->data['SelectedCustomer']['code']))
            {
                $this->data['Customer']['code'] = $this->data['SelectedCustomer']['code'];
                $conditions = array();
                $conditions['Customer.code'] = $this->data['SelectedCustomer']['code'];

                $customer = $this->Customer->find('first', array('conditions' => array('OR' => $conditions)));
                $selected_customer = $customer;
                $this->data['Booking']['customer_id'] = $selected_customer['Customer']['id'];
                $this->set('selected_customer', $customer);
            }

            if (!empty($this->data))
            {
                $this->data['Booking']['user_id'] = $this->Session->read('Auth.User.id');
                if (strlen($this->data['Booking']['date']) == 8)
                {
                    $booking_date_parts = explode('/', $this->data['Booking']['date']);
                    $this->data['Booking']['date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                }
                if (strlen($this->data['Booking']['alo_prepaid_date']) == 8)
                {
                    $booking_date_parts = explode('/', $this->data['Booking']['alo_prepaid_date']);
                    $this->data['Booking']['alo_prepaid_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                }
                if (strlen($this->data['Booking']['alo_fullcharge_date']) == 8)
                {
                    $booking_date_parts = explode('/', $this->data['Booking']['alo_fullcharge_date']);
                    $this->data['Booking']['alo_fullcharge_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                }
                if (strlen($this->data['Booking']['hotel_charge_date']) == 8)
                {
                    $booking_date_parts = explode('/', $this->data['Booking']['hotel_charge_date']);
                    $this->data['Booking']['hotel_charge_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                }
                if (strlen($this->data['Booking']['hotel_prepaid_date']) == 8)
                {
                    $booking_date_parts = explode('/', $this->data['Booking']['hotel_prepaid_date']);
                    $this->data['Booking']['hotel_prepaid_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                }
                if (strlen($this->data['Booking']['hotel_fullcharge_date']) == 8)
                {
                    $booking_date_parts = explode('/', $this->data['Booking']['hotel_fullcharge_date']);
                    $this->data['Booking']['hotel_fullcharge_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                }
                $min_checkin_time = strtotime('+10 years');
                $max_checkout_time = strtotime('-10 years');

                foreach ($this->data['BookingDetail'] as $booking_detail)
                {
                    if (preg_match('/voucher|promotion|khuyến mãi/', mb_strtolower($booking_detail['type'] . ' ' . $booking_detail['quality'])))
                    {
                        continue;
                    }
                    
                    if (strlen($booking_detail['checkin_date']) == 8)
                    {
                        $checkin_date_parts = explode('/', $booking_detail['checkin_date']);
                        $checkin_date = '20' . $checkin_date_parts[2] . '-' . $checkin_date_parts[1] . '-' . $checkin_date_parts[0];
                    }
                    else
                    {
                        $checkin_date = date('Y-m-d');
                    }
                    
                    if (strlen($booking_detail['checkout_date']) == 8)
                    {
                        $checkout_date_parts = explode('/', $booking_detail['checkout_date']);
                        $checkout_date = '20' . $checkout_date_parts[2] . '-' . $checkout_date_parts[1] . '-' . $checkout_date_parts[0];
                    }
                    else
                    {
                        $checkout_date = date('Y-m-d');
                    }
                    
                    if ($min_checkin_time > strtotime($checkin_date))
                    {
                        $min_checkin_time = strtotime($checkin_date);
                        $this->data['Booking']['checkin_date'] = date('Y-m-d', $min_checkin_time);
                    }
                    if ($max_checkout_time < strtotime($checkout_date))
                    {
                        $max_checkout_time = strtotime($checkout_date);
                        $this->data['Booking']['checkout_date'] = date('Y-m-d', $max_checkout_time);
                    }
                }
                if ($this->Booking->save($this->data))
                {
                    foreach ($this->data['BookingDetail'] as $booking_detail)
                    {
                        $booking_detail['booking_id'] = $this->Booking->id;
                        if (strlen($booking_detail['checkin_date']) == 8)
                        {
                            $checkin_date_parts = explode('/', $booking_detail['checkin_date']);
                            $booking_detail['checkin_date'] = '20' . $checkin_date_parts[2] . '-' . $checkin_date_parts[1] . '-' . $checkin_date_parts[0];
                        }
                        if (strlen($booking_detail['checkout_date']) == 8)
                        {
                            $checkout_date_parts = explode('/', $booking_detail['checkout_date']);
                            $booking_detail['checkout_date'] = '20' . $checkout_date_parts[2] . '-' . $checkout_date_parts[1] . '-' . $checkout_date_parts[0];
                        }

                        $booking_detail_data = array('BookingDetail' => $booking_detail);
                        $this->BookingDetail->save($booking_detail_data);
                        $this->BookingDetail->id = null;
                    }
                    
                    $this->flash('Thêm Booking thành công!', '');
                }
            }
        }

        $location_id = 'all';

        if (!empty($this->data['Booking']['location_id']))
        {
            $location_id = $this->data['Booking']['location_id'];
        }

        $hotel_conditions = array();
        if ($location_id != 'all' && is_numeric($location_id))
        {
            $hotel_conditions = array('Hotel.location_id' => $location_id);
        }

        $locations['all'] = 'Chọn địa điểm';
        $locations += $this->Location->find('list');
        $this->set('locations', $locations);

        $hotels['all'] = 'Chọn khách sạn';
        $hotels += $this->Hotel->find('list', array('conditions' => $hotel_conditions));
        $this->set('hotels', $hotels);

        $booking_statuses = $this->BookingStatus->find('list');
        $this->set('bookingStatuses', $booking_statuses);

        $payment_types = $this->PaymentType->find('list');
        $this->set('aloPrepaidPaymentTypes', $payment_types);
        $this->set('aloFullchargePaymentTypes', $payment_types);
        $this->set('hotelPrepaidPaymentTypes', $payment_types);
        $this->set('hotelFullchargePaymentTypes', $payment_types);

        $this->set('selected_customer', $selected_customer);
    }

    function edit($id)
    {
        $this->Booking->id = $id;
        $selected_customer = null;
        if (empty($this->data))
        {
            $this->data = $this->Booking->read();
            $this->data['Booking']['date'] = date('d/m/y', strtotime($this->data['Booking']['date']));
            $this->data['Booking']['alo_prepaid_date'] = date('d/m/y', strtotime($this->data['Booking']['alo_prepaid_date']));
            $this->data['Booking']['alo_fullcharge_date'] = date('d/m/y', strtotime($this->data['Booking']['alo_fullcharge_date']));
            $this->data['Booking']['hotel_charge_date'] = date('d/m/y', strtotime($this->data['Booking']['hotel_charge_date']));
            $this->data['Booking']['hotel_prepaid_date'] = date('d/m/y', strtotime($this->data['Booking']['hotel_prepaid_date']));
            $this->data['Booking']['hotel_fullcharge_date'] = date('d/m/y', strtotime($this->data['Booking']['hotel_fullcharge_date']));

            $this->data['Booking']['alo_prepaid_amount'] = (float) $this->data['Booking']['alo_prepaid_amount'];
            $this->data['Booking']['alo_fullcharge_amount'] = (float) $this->data['Booking']['alo_fullcharge_amount'];
            $this->data['Booking']['hotel_charge_amount'] = (float) $this->data['Booking']['hotel_charge_amount'];
            $this->data['Booking']['hotel_prepaid_amount'] = (float) $this->data['Booking']['hotel_prepaid_amount'];
            $this->data['Booking']['hotel_fullcharge_amount'] = (float) $this->data['Booking']['hotel_fullcharge_amount'];
            for ($i = 0; $i < sizeof($this->data['BookingDetail']); $i++)
            {
                $this->data['BookingDetail'][$i]['checkin_date'] = date('d/m/y', strtotime($this->data['BookingDetail'][$i]['checkin_date']));
                $this->data['BookingDetail'][$i]['checkout_date'] = date('d/m/y', strtotime($this->data['BookingDetail'][$i]['checkout_date']));
                $this->data['BookingDetail'][$i]['cost'] = (float) $this->data['BookingDetail'][$i]['cost'];
                $this->data['BookingDetail'][$i]['original_cost'] = (float) $this->data['BookingDetail'][$i]['original_cost'];
            }
            
            $selected_customer = array('Customer' => $this->data['Customer']);
            $this->set('selected_customer', $selected_customer);
            $this->data['Customer'] = null;
        }
        else
        {
            $action = !empty($this->data['Action']['do']) ? $this->data['Action']['do'] : '';
            if ($action == 'edit_booking')
            {
                if (!empty($this->data['SelectedCustomer']['code']))
                {
                    $this->data['Customer']['code'] = $this->data['SelectedCustomer']['code'];
                    $conditions = array();
                    $conditions['Customer.code'] = $this->data['SelectedCustomer']['code'];

                    $customer = $this->Customer->find('first', array('conditions' => array('OR' => $conditions)));
                    $selected_customer = $customer;
                    $this->data['Booking']['customer_id'] = $selected_customer['Customer']['id'];
                    $this->set('selected_customer', $customer);
                }
                if (!empty($this->data))
                {
                    $this->data['Booking']['user_id'] = $this->Session->read('Auth.User.id');
                    if (strlen($this->data['Booking']['date']) == 8)
                    {
                        $booking_date_parts = explode('/', $this->data['Booking']['date']);
                        $this->data['Booking']['date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                    }
                    if (strlen($this->data['Booking']['alo_prepaid_date']) == 8)
                    {
                        $booking_date_parts = explode('/', $this->data['Booking']['alo_prepaid_date']);
                        $this->data['Booking']['alo_prepaid_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                    }
                    if (strlen($this->data['Booking']['alo_fullcharge_date']) == 8)
                    {
                        $booking_date_parts = explode('/', $this->data['Booking']['alo_fullcharge_date']);
                        $this->data['Booking']['alo_fullcharge_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                    }
                    if (strlen($this->data['Booking']['hotel_charge_date']) == 8)
                    {
                        $booking_date_parts = explode('/', $this->data['Booking']['hotel_charge_date']);
                        $this->data['Booking']['hotel_charge_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                    }
                    if (strlen($this->data['Booking']['hotel_prepaid_date']) == 8)
                    {
                        $booking_date_parts = explode('/', $this->data['Booking']['hotel_prepaid_date']);
                        $this->data['Booking']['hotel_prepaid_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                    }
                    if (strlen($this->data['Booking']['hotel_fullcharge_date']) == 8)
                    {
                        $booking_date_parts = explode('/', $this->data['Booking']['hotel_fullcharge_date']);
                        $this->data['Booking']['hotel_fullcharge_date'] = '20' . $booking_date_parts[2] . '-' . $booking_date_parts[1] . '-' . $booking_date_parts[0];
                    }
                    $min_checkin_time = strtotime('+10 years');
                    $max_checkout_time = strtotime('-10 years');

                    foreach ($this->data['BookingDetail'] as $booking_detail)
                    {
                        if (preg_match('/voucher|promotion|khuyến mãi/', mb_strtolower($booking_detail['type'] . ' ' . $booking_detail['quality'])))
                        {
                            continue;
                        }
                        
                        if (strlen($booking_detail['checkin_date']) == 8)
                        {
                            $checkin_date_parts = explode('/', $booking_detail['checkin_date']);
                            $checkin_date = '20' . $checkin_date_parts[2] . '-' . $checkin_date_parts[1] . '-' . $checkin_date_parts[0];
                        }
                        else
                        {
                            $checkin_date = date('Y-m-d');
                        }

                        if (strlen($booking_detail['checkout_date']) == 8)
                        {
                            $checkout_date_parts = explode('/', $booking_detail['checkout_date']);
                            $checkout_date = '20' . $checkout_date_parts[2] . '-' . $checkout_date_parts[1] . '-' . $checkout_date_parts[0];
                        }
                        else
                        {
                            $checkout_date = date('Y-m-d');
                        }
                        
                        if ($min_checkin_time > strtotime($checkin_date))
                        {
                            $min_checkin_time = strtotime($checkin_date);
                            $this->data['Booking']['checkin_date'] = date('Y-m-d', $min_checkin_time);
                        }
                        if ($max_checkout_time < strtotime($checkout_date))
                        {
                            $max_checkout_time = strtotime($checkout_date);
                            $this->data['Booking']['checkout_date'] = date('Y-m-d', $max_checkout_time);
                        }
                    }
                    if ($this->Booking->save($this->data))
                    {
                        if (!empty($this->data['BookingDetail']))
                        {
                            $this->BookingDetail->deleteAll(array('BookingDetail.booking_id' => $this->Booking->id));
                            foreach ($this->data['BookingDetail'] as $booking_detail)
                            {
                                $booking_detail['booking_id'] = $this->Booking->id;
                                if (strlen($booking_detail['checkin_date']) == 8)
                                {
                                    $checkin_date_parts = explode('/', $booking_detail['checkin_date']);
                                    $booking_detail['checkin_date'] = '20' . $checkin_date_parts[2] . '-' . $checkin_date_parts[1] . '-' . $checkin_date_parts[0];
                                }
                                if (strlen($booking_detail['checkout_date']) == 8)
                                {
                                    $checkout_date_parts = explode('/', $booking_detail['checkout_date']);
                                    $booking_detail['checkout_date'] = '20' . $checkout_date_parts[2] . '-' . $checkout_date_parts[1] . '-' . $checkout_date_parts[0];
                                }
                                $booking_detail_data = array('BookingDetail' => $booking_detail);
                                $this->BookingDetail->save($booking_detail_data);
                                $this->BookingDetail->id = null;
                            }
                        }
                        $this->flash('Sửa Booking thành công!', '');
                    }
                }
            }
        }
        $today = date('d/m/y', time());
        $this->set('today', $today);

        if (empty($this->data['Booking']['date']))
        {
            $this->data['Booking']['date'] = $today;
        }

        $customer_code = $this->AloCode->generateCustomerCode();
        $this->set('customer_code', $customer_code);

        $alo_booking_code = $this->AloCode->generateBookingCode();
        $this->set('alo_booking_code', $alo_booking_code);

        $action = !empty($this->data['Action']['do']) ? $this->data['Action']['do'] : '';

        $customers = $this->Customer->find('all');
        $this->set('customers', $customers);

        //$selected_customer = null;

        if ($action == 'add_customer')
        {
            $this->layout = 'ajax';
            if ($this->Customer->save($this->data))
            {
                //$this->flash('Tạo khách hàng thành công!', '');
                $this->set('success_msg', 'Tạo khách hàng thành công!');
                $customer['Customer'] = $this->data['Customer'];
                $customer['Customer']['id'] = $this->Customer->id;
                $this->data['Customer'] = null;
                $this->set('selected_customer', $customer);
                $selected_customer = $customer;
            }
            else
            {
                if (!empty($this->params['named']['query']))
                {
                    $query = $this->params['named']['query'];
                    //$query = htmlspecialchars_decode($query);
                    $this->set('query', $query);

                    $conditions = array();
                    //$conditions['Customer.information LIKE'] = '%' . mysql_real_escape_string(trim($query)) . '%';
                    $query_string = explode(',', $query);
                    $count = 1;
                    foreach ($query_string as $search_string)
                    {
                        $conditions[] = array('Customer.information LIKE' => "%" . mysql_real_escape_string(trim($search_string)) . "%");
                        $count++;
                    }

                    $customer = $this->Customer->find('first', array('conditions' => array('OR' => $conditions)));
                    $selected_customer = $customer;
                    $this->set('selected_customer', $customer);
                }
            }
            $this->render('select_customer');
        }

        else if ($action == 'find_customer')
        {
            $this->layout = 'ajax';
            if (!empty($this->params['named']['query']))
            {
                $query = $this->params['named']['query'];
                //$query = htmlspecialchars_decode($query);
                $this->set('query', $query);

                $conditions = array();
                //$conditions['Customer.information LIKE'] = '%' . mysql_real_escape_string(trim($query)) . '%';
                $query_string = explode(',', $query);
                $count = 1;
                foreach ($query_string as $search_string)
                {
                    $conditions[] = array('Customer.information LIKE' => "%" . mysql_real_escape_string(trim($search_string)) . "%");
                    $count++;
                }

                $customer = $this->Customer->find('first', array('conditions' => array('OR' => $conditions)));
                $selected_customer = $customer;
                $this->set('selected_customer', $customer);
            }
            $this->render('select_customer');
        }

        else if ($action == 'update_booking_info_left')
        {
            $this->layout = 'ajax';

            $location_id = 'all';

            if (!empty($this->params['named']['location_id']))
            {
                $location_id = $this->params['named']['location_id'];
                $this->data['Booking']['location_id'] = $location_id;
            }

            $hotel_conditions = array();
            if ($location_id != 'all' && is_numeric($location_id))
            {
                $hotel_conditions = array('Hotel.location_id' => $location_id);
            }

            $locations['all'] = 'Chọn địa điểm';
            $locations += $this->Location->find('list');
            $this->set('locations', $locations);

            $hotels['all'] = 'Chọn khách sạn';
            $hotels += $this->Hotel->find('list', array('conditions' => $hotel_conditions));
            $this->set('hotels', $hotels);

            $this->render('booking_info_left');
        }

        $location_id = 'all';

        if (!empty($this->data['Booking']['location_id']))
        {
            $location_id = $this->data['Booking']['location_id'];
        }

        $hotel_conditions = array();
        if ($location_id != 'all' && is_numeric($location_id))
        {
            $hotel_conditions = array('Hotel.location_id' => $location_id);
        }

        $locations['all'] = 'Chọn địa điểm';
        $locations += $this->Location->find('list');
        $this->set('locations', $locations);

        $hotels['all'] = 'Chọn khách sạn';
        $hotels += $this->Hotel->find('list', array('conditions' => $hotel_conditions));
        $this->set('hotels', $hotels);

        $booking_statuses = $this->BookingStatus->find('list');
        $this->set('bookingStatuses', $booking_statuses);

        $payment_types = $this->PaymentType->find('list');
        $this->set('aloPrepaidPaymentTypes', $payment_types);
        $this->set('aloFullchargePaymentTypes', $payment_types);
        $this->set('hotelPrepaidPaymentTypes', $payment_types);
        $this->set('hotelFullchargePaymentTypes', $payment_types);

        $this->set('selected_customer', $selected_customer);
    }

    function show($id)
    {
        if (!empty($this->params['named']['action']))
        {
            $action = $this->params['named']['action'];
            if ($action == 'change_booking_status')
            {
                if (isset($this->params['named']['status']))
                {
                    $this->Booking->id = $id;
                    $data['booking_status_id'] = $this->params['named']['status'];
                    $this->Booking->save($data);
                }
            }
        }
        $booking = $this->Booking->findById($id);
        if (!empty($booking))
        {
            if (empty($booking['Booking']['alo_exchange_rate']))
            {
                $booking['Booking']['alo_exchange_rate'] = 1;
            }
            if (empty($booking['Booking']['hotel_exchange_rate']))
            {
                $booking['Booking']['hotel_exchange_rate'] = 1;
            }
            $total_days = 0;
            $total_price = 0;
            $total_original_price = 0;
            foreach ($booking['BookingDetail'] as $booking_detail)
            {
                $total_days += $booking_detail['days'];
                $total_price += $booking_detail['price'];
                $total_original_price += $booking_detail['original_price'];
            }

            $total_price_usd = 0;
            $total_price_vnd = 0;
            if ($booking['Booking']['currency'] == 'USD')
            {
                $total_price_usd = $total_price;
                $total_price_vnd = $total_price_usd * $booking['Booking']['alo_exchange_rate'];

                $total_original_price_usd = $total_original_price;
                $total_original_price_vnd = $total_original_price_usd * $booking['Booking']['hotel_exchange_rate'];
            }
            else
            {
                $total_price_vnd = $total_price;
                $total_price_usd = $total_price_vnd / $booking['Booking']['alo_exchange_rate'];

                $total_original_price_vnd = $total_original_price;
                $total_original_price_usd = $total_original_price_vnd / $booking['Booking']['hotel_exchange_rate'];
            }

            $profit_usd = $total_price_usd - $total_original_price_usd;
            $profit_vnd = $total_price_vnd - $total_original_price_vnd;

            $this->set('total_price_usd', $total_price_usd);
            $this->set('total_price_vnd', $total_price_vnd);

            $this->set('total_original_price_usd', $total_original_price_usd);
            $this->set('total_original_price_vnd', $total_original_price_vnd);

            $this->set('profit_usd', $profit_usd);
            $this->set('profit_vnd', $profit_vnd);

            $alo_prepaid_payment_type = $this->PaymentType->findById($booking['Booking']['alo_prepaid_payment_type_id']);
            $this->set('alo_prepaid_payment_type', $alo_prepaid_payment_type);
            
            $alo_fullcharge_payment_type = $this->PaymentType->findById($booking['Booking']['alo_fullcharge_payment_type_id']);
            $this->set('alo_fullcharge_payment_type', $alo_fullcharge_payment_type);

            $hotel_prepaid_payment_type = $this->PaymentType->findById($booking['Booking']['hotel_prepaid_payment_type_id']);
            $this->set('hotel_prepaid_payment_type', $hotel_prepaid_payment_type);

            $hotel_fullcharge_payment_type = $this->PaymentType->findById($booking['Booking']['hotel_fullcharge_payment_type_id']);
            $this->set('hotel_fullcharge_payment_type', $hotel_fullcharge_payment_type);
            
            $this->set('total_days', $total_days);
            $this->set('booking', $booking);

            $this->data = $booking;
        }
        else
        {
            $this->flash('Không tìm thấy Booking này', '/bookings');
        }
        $booking_statuses = $this->BookingStatus->find('list');
        $this->set('bookingStatuses', $booking_statuses);
    }

    function send($id, $type)
    {
        $booking = $this->Booking->find('first', array('conditions' => array('Booking.id' => $id), 'recursive' => 2));
        $email_from = 'booking@alobooking.net';
        if (!empty($booking))
        {
            if (empty($booking['Booking']['alo_exchange_rate']))
            {
                $booking['Booking']['alo_exchange_rate'] = 1;
            }
            if (empty($booking['Booking']['hotel_exchange_rate']))
            {
                $booking['Booking']['hotel_exchange_rate'] = 1;
            }
            $total_days = 0;
            $total_price = 0;
            $total_original_price = 0;
            foreach ($booking['BookingDetail'] as $booking_detail)
            {
                $total_days += $booking_detail['days'];
                $total_price += $booking_detail['price'];
                $total_original_price += $booking_detail['original_price'];
            }

            $total_price_usd = 0;
            $total_price_vnd = 0;
            if ($booking['Booking']['currency'] == 'USD')
            {
                $total_price_usd = $total_price;
                $total_price_vnd = $total_price_usd * $booking['Booking']['alo_exchange_rate'];

                $total_original_price_usd = $total_original_price;
                $total_original_price_vnd = $total_original_price_usd * $booking['Booking']['hotel_exchange_rate'];
            }
            else
            {
                $total_price_vnd = $total_price;
                $total_price_usd = $total_price_vnd / $booking['Booking']['alo_exchange_rate'];

                $total_original_price_vnd = $total_original_price;
                $total_original_price_usd = $total_original_price_vnd / $booking['Booking']['hotel_exchange_rate'];
            }

            $profit_usd = $total_price_usd - $total_original_price_usd;
            $profit_vnd = $total_price_vnd - $total_original_price_vnd;

            $this->set('total_price_usd', $total_price_usd);
            $this->set('total_price_vnd', $total_price_vnd);

            $this->set('total_original_price_usd', $total_original_price_usd);
            $this->set('total_original_price_vnd', $total_original_price_vnd);

            $this->set('profit_usd', $profit_usd);
            $this->set('profit_vnd', $profit_vnd);
            
            $send_title = 'Email';
            $lang = 'vi';
            $email_template = 'confirm_' . $lang;
            $receiver_name = '';
            $receiver_email = '';
            $email_title = '';
            
            if (!empty($this->params['pass'][1]))
            {
                $action = $this->params['pass'][1];
                if ($action == 'confirm')
                {
                    $lang = $this->params['named']['lang'];
                    $send_title = 'Confirm khách - ' . strtoupper($lang);
                    $email_template = 'confirm_' . $lang;
                    $receiver_name = $booking['Customer']['full_name'];
                    $receiver_email = $booking['Customer']['email'];
                    $email_title = "Xac nhan dat phong: {$booking['Hotel']['name']} | {$booking['Customer']['full_name']} | {$booking['Booking']['checkin_date']}";
                    $email_from = $this->Session->read('Auth.User.email');
                }

                if ($action == 'send_booking')
                {
                    $email_template = 'send_booking';
                    $send_title = 'Send booking';
                    $receiver_name = $booking['Hotel']['name'];
                    $receiver_email = $booking['Hotel']['email'];
                    $email_title = 'Booking room ' . date('d/m/Y', strtotime($booking['Booking']['checkin_date'])) . ' - ' . mb_strtoupper($booking['Customer']['full_name']);
                }
            }
            $this->set('receiver_name', $receiver_name);
            $this->set('receiver_email', $receiver_email);
            $this->set('email_title', $email_title);
            $this->set('email_template', $email_template);
            $this->set('lang', $lang);
            $this->set('send_title', $send_title);
            $this->set('booking', $booking);
        }
        else
        {
            $this->flash('Không tìm thấy Booking này', '/bookings');
        }

        if (!empty($this->data['Email']))
        {
            $this->Email->from = $email_from;
            $this->Email->replyTo = $email_from;
            $this->Email->to = $this->data['Email']['receiver_email'];
            $this->Email->bcc = array($email_from);
            $this->Email->subject = $this->data['Email']['title'];
            $this->Email->template = $email_template;
            $this->Email->additionalParams = "-f $email_from";

            $this->Email->sendAs = 'both';
            $this->set('booking', $booking);

            /* SMTP Options */
            $this->Email->smtpOptions = array(
                'port'=>'465',
                'timeout'=>'30',
                'host' => 'ssl://smtp.gmail.com',
                'username'=>'smtp@coffeemugvn.com',
                'password'=>'smtp@coffeemugvn.com',
            );

            //debug($this->Email);
            //$this->Email->delivery = 'debug';

            $this->Email->send();

            $this->set('smtp_errors', $this->Email->smtpError);

        }
    }

    function eticket($id)
    {
        $this->layout = 'blank';
        $booking = $this->Booking->find('first', array('conditions' => array('Booking.id' => $id), 'recursive' => 2));
        if (!empty($booking))
        {
            if (empty($booking['Booking']['alo_exchange_rate']))
            {
                $booking['Booking']['alo_exchange_rate'] = 1;
            }
            if (empty($booking['Booking']['hotel_exchange_rate']))
            {
                $booking['Booking']['hotel_exchange_rate'] = 1;
            }
            $total_days = 0;
            $total_price = 0;
            $total_original_price = 0;
            foreach ($booking['BookingDetail'] as $booking_detail)
            {
                $total_days += $booking_detail['days'];
                $total_price += $booking_detail['price'];
                $total_original_price += $booking_detail['original_price'];
            }

            $total_price_usd = 0;
            $total_price_vnd = 0;
            if ($booking['Booking']['currency'] == 'USD')
            {
                $total_price_usd = $total_price;
                $total_price_vnd = $total_price_usd * $booking['Booking']['alo_exchange_rate'];

                $total_original_price_usd = $total_original_price;
                $total_original_price_vnd = $total_original_price_usd * $booking['Booking']['hotel_exchange_rate'];
            }
            else
            {
                $total_price_vnd = $total_price;
                $total_price_usd = $total_price_vnd / $booking['Booking']['alo_exchange_rate'];

                $total_original_price_vnd = $total_original_price;
                $total_original_price_usd = $total_original_price_vnd / $booking['Booking']['hotel_exchange_rate'];
            }

            $profit_usd = $total_price_usd - $total_original_price_usd;
            $profit_vnd = $total_price_vnd - $total_original_price_vnd;

            $this->set('total_price_usd', $total_price_usd);
            $this->set('total_price_vnd', $total_price_vnd);

            $this->set('total_original_price_usd', $total_original_price_usd);
            $this->set('total_original_price_vnd', $total_original_price_vnd);

            $this->set('profit_usd', $profit_usd);
            $this->set('profit_vnd', $profit_vnd);
            
            $this->set('booking', $booking);
        }
        else
        {
            $this->flash('Không tìm thấy Booking này', '/bookings/eticket/' . $id);
        }
    }

    function delete($id)
    {
        if ($this->Session->read('Auth.User.role') == 'admin')
        {
            //$this->Booking->delete($id);
        }
        $this->redirect(array('controller' => 'bookings', 'action' => 'index'));
    }
}
?>
